package com.itany.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/11/14 10:33
 * Version:1.0-SNAPSHOT
 * Description:
 */
public class Test10 {

    public static void main(String[] args) throws SQLException {
        test();
        test2();
    }

    public static void test(){
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            long begin = System.currentTimeMillis();
            for(int i = 0; i < 1000; i++) {
                ps = conn.prepareStatement(sql);
                ps.setString(1, "test");
                ps.setString(2, "123456");
                ps.setString(3, "13812345678");
                ps.setString(4, "江苏-南京");
                ps.executeUpdate();
            }
            long end = System.currentTimeMillis();
            // 1307毫秒
            System.out.println("执行操作共耗费了"+(end-begin)+"毫秒");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(conn,ps,null);
        }
    }

    public static void test2() throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append("   (username,password,phone,address)")
                    .append(" values ")
                    .append("   (?,?,?,?)")
                    .toString();
            long begin = System.currentTimeMillis();
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            for(int i = 0; i < 1000; i++) {
                ps.setString(1, "test");
                ps.setString(2, "123456");
                ps.setString(3, "13812345678");
                ps.setString(4, "江苏-南京");
                // 将ps对象添加到缓冲区
                ps.addBatch();
            }
            // 批量执行
            ps.executeBatch();
            conn.commit();
            long end = System.currentTimeMillis();
            // 179毫秒
            System.out.println("执行操作共耗费了"+(end-begin)+"毫秒");
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback();
        } finally {
            JDBCUtil.close(conn,ps,null);
        }
    }

}
